/* 
 * Copyright 2005 - 2009 Terracotta, Inc. 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
 * use this file except in compliance with the License. You may obtain a copy 
 * of the License at 
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0 
 *   
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
 * License for the specific language governing permissions and limitations 
 * under the License.
 * 
 */

package com.baoxian.task.job.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.baoxian.task.job.datasource.JdbcUtil;

import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * 释放任务的工作
 * </p>
 *
 * @author Xiong Neng
 */
public class ReleaseTaskJob implements Job {

    private static Logger log = LoggerFactory.getLogger(ReleaseTaskJob.class);

    public ReleaseTaskJob() {
    }

    /**
     * 释放超时的任务
     *
     * @param context jobcontext
     * @throws JobExecutionException
     */
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobKey jobKey = context.getJobDetail().getKey();
        log.info("JobKey的值为: " + jobKey + "  | 实际的触发时间： " + sdf.format(new Date()));

        //  从JobDataMap中获取超时的参数
        JobDataMap data = context.getJobDetail().getJobDataMap();
        //核保历史任务，报价历史任务的过期天数
        int timeoutDays = data.getInt("timeoutDays");
        //单方报价，多方报价过期天数
        int baojiaTimeoutDays=data.getInt("baojiaTimeoutDays");

        log.info("---------->>获取到的核保，报价历史任务超时参数为:" + timeoutDays);
        log.info("---------->>获取到的单方，多方报价超时参数为:" + baojiaTimeoutDays);
        // 接下来进行数据库操作处理
        /** 核保历史任务，报价历史任务表的删除*/
        String lastUpdated = getDayBefore(timeoutDays);
        deleteTaskJob("quote_task",lastUpdated);
        deleteTaskJob("insure_task",lastUpdated);
        /** 单方报价表，多方报价表的删除*/
        String baojiaLastUpdated = getDayBefore(baojiaTimeoutDays);
        deleteTaskJob("vehicle_enquiry",baojiaLastUpdated);
       deleteTaskJob("ins_multi_quote",baojiaLastUpdated);

        log.info("---------定时job执行完毕----------");
    }

    private void deleteTaskJob(String tableName,String last_updated) {

        String delSql = " delete from "+tableName+"  where last_updated < ? limit 100 ";

        Connection connection=null;
        PreparedStatement pstmt=null;

        try {
            int num = 0;
            connection = JdbcUtil.getConnection();
            pstmt = connection.prepareStatement(delSql);
            pstmt.setString(1, last_updated);
            boolean isRun=true;
            while (isRun){
                num = pstmt.executeUpdate();
                log.info("--------成功删除"+tableName+"表中的 " + num + " 条数据");
                if(num>0){
                    isRun=true;
                }else{
                    isRun=false;
                }
            }



        } catch (SQLException e) {
            log.error("------删除数据异常------", e);
        }finally {
            if(pstmt!=null){
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    log.error(e.getMessage(),e);

                }
            }

            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    log.error(e.getMessage(),e);
                }
            }


        }
    }

    /**
     * 获取过期日期字符串
     *
     * @param timeoutDays 过期的天数
     * @return 获取过期日期字符串
     */
    private String getDayBefore(int timeoutDays) {
        //获取1970-01-01 至今的毫秒数
        long toTodayTime = System.currentTimeMillis();
        //超时所消耗的时间
        long outDayTime = timeoutDays * 24 * 3600 * 1000L;
        //获取1970-01-01到过期那天的毫秒数
        long toOutDayTime = toTodayTime - outDayTime;
        //获取过期那天的日期
        Date outDayDate = new Date(toOutDayTime);
        //转换为字符串
        String timeoutStr = sdf.format(outDayDate);
        log.info("获取的超时时间字符串为：" + timeoutStr);
        return timeoutStr;
    }

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
